package com.bys.security;

import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bys.constant.CrmSystemConstant;
import com.bys.constant.HttpContant;
import com.bys.exception.BysOaSystemException;
import com.bys.system.model.SysUserModel;
import com.bys.system.service.ISysMenuService;
import com.bys.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserModel userModel = sysUserService.getOne(Wrappers.lambdaQuery(SysUserModel.class).eq(SysUserModel::getIsDeleted, Boolean.FALSE).eq(SysUserModel::getUsername, username).or().eq(SysUserModel::getEmail,username).eq(SysUserModel::getIsDeleted, Boolean.FALSE));
        Optional.ofNullable(userModel).orElseThrow(() -> new BysOaSystemException("用户不存在"));
        if(!CrmSystemConstant.ENABLE_STATUS.equals(userModel.getStatus())){
            throw new BysOaSystemException(HttpContant.NO_PERMISSION, "账号已停用!!");
        }
        List<String> permissions = sysMenuService.findUserPermission(userModel.getId());
        // 添加权限
        Set<CrmGrantedAuthority> auths = new HashSet<>();
        permissions.forEach( p ->{
            auths.add(new CrmGrantedAuthority(p));
        });

        return new CrmUser(userModel,auths);
    }
}
